import { checkPayIsValid } from '@/api/user;
import router from '@/utils/router';
//是否继续轮询
let isContinue = true;
//轮询只能有一个
let isOne = false;
let errorCount = 0;
let isOver = false;

//检查支付订单有效性
export const usePayTimer = () => {
  const startPayTimer = (payOrder, deviceId) => {
    if (isOne) return;
    isOne = true;
    isOver = false;
    checkOrder(payOrder, deviceId);
  };

  const checkOrder = async (payOrder, deviceId) => {
    if (!isContinue) return false;
    console.log('--轮询查询押金中--');
    try {
      const res = await checkPayIsValid(payOrder.data.orderUuid);
      if (!res.data) {
        setTimeout(() => {
          checkOrder(payOrder, deviceId);
        }, 5000);
      } else {
        clearPayTimer();
        router.replace('/pages/popup/popup?id=' + deviceId);
        isOver = true;
        return;
      }
    } catch (error) {
      console.log(error, '--轮询查询押金异常--');
      setTimeout(() => {
        checkOrder(payOrder, deviceId);
        if (isOver) return;
        errorCount++;
        if (errorCount > 3) {
          clearPayTimer();
          alert(JSON.stringify(error));
          router.replace('/pages/map/map');
        }
      }, 6000);
    }
  };

  const clearPayTimer = () => {
    isContinue = false;
    errorCount = 0;
    isOne = false;
    isOver = false;
  };

  const setContinue = () => {
    isContinue = true;
  };

  return { startPayTimer, clearPayTimer, setContinue };
};
